#!/usr/bin/env bash

#########################################################
# get the real path about files in common
COMMON_DIR=$(cd `dirname $BASH_SOURCE`; pwd)
if [ ! -n ${UBUNTU_SERVER_DEPLOY} ]; then
	cd ${COMMON_DIR}
	source ../init.sh
	# return it back
	cd ${CUR_DIR}
fi
#########################################################

# make sure the temp dir is existing
if [ ! -n "${PHP_TEMP_DIR}" ]; then
	PHP_TEMP_DIR=${CUR_DIR}/temp
fi

if [ ! -d "${PHP_TEMP_DIR}" ]; then
	mkdir "${PHP_TEMP_DIR}" -p
fi

php_download() {
	download_uncompress ${PHP_TEMP_DIR} ${PHP_PKG_NAME} ${PHP_SOURCE}
}

php_install_pkgs() {
	apt-get install -y gcc-4.7 g++ automake autoconf libtool
	apt-get install -y libxml2-dev bzip2 libcurl4-openssl-dev
	apt-get install -y libcurl4-gnutls-dev
	apt-get install -y libjpeg-dev libpng-dev libxpm-dev libfreetype6-dev libt1-dev libmcrypt-dev libmysql++-dev libxslt1-dev libbz2-dev libghc-regex-pcre-dev libicu-dev
	if [ -n "${PHP_REQ_PKGS}" ]; then
		apt-get install -y "${PHP_REQ_PKGS}"
	fi
}

php_install() {
	local rebuild=0
	[ -n "${1}" ] && rebuild=1

	if [ ! -d "${PHP_TEMP_DIR}" ]; then
		mkdir "${PHP_TEMP_DIR}" -p
	fi

	if [[ ${rebuild} -gt 0 || ! -d ${PHP_HOME} ]]; then
		php_install_pkgs
		cd "${PHP_TEMP_DIR}"
		php_download

		cd "${PHP_TEMP_DIR}/${PHP_PKG_NAME}"
		${PHP_CONF_CMD}
		make
		make install
	fi

	php_mk_ini
	php_mk_bin

	php_mk_fpm_conf
	php_mk_sh
}

php_mk_ini() {
	if [ ! -d "${PHP_HOME}" ]; then
		echo "Can't find php install dir ${PHP_HOME}"
		return 1
	fi

	if [ ! -d "${PHP_TEMP_DIR}/${PHP_PKG_NAME}" ]; then
		php_download
	fi

	local php=${PHP_HOME}/bin/php
	IFS=""
	local phpinfo=$(${php} -i)
	local extdir=$(echo ${phpinfo} | grep -Po "^extension_dir .*" | awk '{print $3}')
	local quote_extdir=${extdir////\\/}

	local quote_timezone=${TIMEZONE////\\/}

	local phpini_src=${PHP_TEMP_DIR}/${PHP_PKG_NAME}/php.ini-production
	local phpini_target=${PHP_HOME}/lib/php.ini

	local replace_words=

	if [ ! -f "${phpini_target}" ]; then
		cp ${phpini_src} ${phpini_target}
		###################################
		# Must
		# expose_php = On
		sed -i "s/^expose_php =.*$/expose_php = Off/g" ${phpini_target}
		# ; extension_dir = "ext"
		sed -i "s/^; extension_dir = \"ext\".*$/extension_dir = ${quote_extdir}/g" ${phpini_target}
		# ;cgi.fix_pathinfo=1
		sed -i "s/^;cgi.fix_pathinfo=.*$/cgi.fix_pathinfo=1/g" ${phpini_target}
		# ;date.timezone =
		sed -i "s/;date.timezone =.*$/date.timezone = ${quote_timezone}/g" ${phpini_target}

		replace_words=$(str_push "|" ${replace_words} "expose_php|extension_dir|cgi.fix_pathinfo|date.timezone")

		# ;default_charset = .*
		if [ -n "${PHP_INI_DEFAULT_CHARSET}" ]; then
			replace_words=$(str_push "|" ${replace_words} "default_charset")
			sed -i "s/;default_charset =.*$/default_charset = \"${PHP_INI_DEFAULT_CHARSET}\"/g" ${phpini_target}
		fi
	else
		###################################
		# Must
		# expose_php = On
		sed -i "s/^expose_php =.*$/expose_php = Off/g" ${phpini_target}
		# ; extension_dir = "ext"
		sed -i "s/^extension_dir =.*$/extension_dir = ${quote_extdir}/g" ${phpini_target}
		# ;cgi.fix_pathinfo=1
		sed -i "s/^cgi.fix_pathinfo=.*$/cgi.fix_pathinfo=1/g" ${phpini_target}
		# ;date.timezone =
		sed -i "s/date.timezone =.*$/date.timezone = ${quote_timezone}/g" ${phpini_target}

		replace_words=$(str_push "|" ${replace_words} "expose_php|extension_dir|cgi.fix_pathinfo|date.timezone")

		# default_charset = .*
		if [ -n "${PHP_INI_DEFAULT_CHARSET}" ]; then
			replace_words=$(str_push "|" ${replace_words} "default_charset")
			sed -i "s/default_charset =.*$/default_charset = \"${PHP_INI_DEFAULT_CHARSET}\"/g" ${phpini_target}
		fi
	fi

	###################################
	# Use define
	# max_execution_time = 30
	# 30 seconds ~ 5 minutes
	if [ $(is_int ${PHP_INI_MAX_EXECUTION_TIME} 29 301) -eq 1 ]; then
		replace_words=$(str_push "|" ${replace_words} "max_execution_time")
		sed -i "s/^max_execution_time = .*$/max_execution_time = ${PHP_INI_MAX_EXECUTION_TIME}/g" ${phpini_target}
	fi
	# max_input_time = 60
	# 30 seconds ~ 5 minutes
	if [ $(is_int ${PHP_INI_MAX_INPUT_TIME} 29 301) -eq 1 ]; then
		replace_words=$(str_push "|" ${replace_words} "max_input_time")
		sed -i "s/^max_input_time = .*$/max_input_time = ${PHP_INI_MAX_INPUT_TIME}/g" ${phpini_target}
	fi
	# post_max_size = .*
	# [\d]+M
	# 1-9G
	if [ $(is_match ${PHP_INI_POST_MAX_SIZE} "^([\d]+M|[1-9]G)$") -eq 1 ]; then
		replace_words=$(str_push "|" ${replace_words} "post_max_size")
		sed -i "s/^post_max_size = .*$/post_max_size = ${PHP_INI_POST_MAX_SIZE}/g" ${phpini_target}
	fi
	# upload_max_filesize = .*
	# [\d]+M
	# 1-9G
	if [ $(is_match ${PHP_INI_UPLOAD_MAX_SIZE} "^([\d]+M|[1-9]G)$") -eq 1 ]; then
		replace_words=$(str_push "|" ${replace_words} "upload_max_filesize")
		sed -i "s/^upload_max_filesize = .*$/upload_max_filesize = ${PHP_INI_UPLOAD_MAX_SIZE}/g" ${phpini_target}
	fi

	echo "modified settings in ${phpini_target}"
	grep -P "^(${replace_words})" ${phpini_target}

}

php_mk_bin() {
	if [ ! -d "${PHP_HOME}" ]; then
		echo "Can't find php install dir ${PHP_HOME}"
		return 1
	fi

	if [ ! -d "${PHP_TEMP_DIR}/${PHP_PKG_NAME}" ]; then
		php_download
	fi

	local phpbin_src=${PHP_HOME}/bin/php
	local phpbin_link=/usr/local/bin/${PHP_BIN_PREFIX}

	local phpize_src=${PHP_HOME}/bin/phpize
	local phpize_link=/usr/local/bin/${PHP_BIN_PREFIX}ize

	local phpfpm_src=${PHP_HOME}/sbin/php-fpm
	local phpfpm_link=/usr/local/sbin/${PHP_BIN_PREFIX}-fpm

	local pecl_src=${PHP_HOME}/bin/pecl
	local pecl_link=/usr/local/bin/${PHP_BIN_PREFIX}-pecl

	local pear_src=${PHP_HOME}/bin/pear
	local pear_link=/usr/local/bin/${PHP_BIN_PREFIX}-pear

	local ver_regex="^PHP (\d+\.?)+\b"

	if [ -f "${phpbin_link}" ]; then
		local link_ver=$(${phpbin_link} -version | grep -Po ${ver_regex})
		local src_ver=$(${phpbin_src} -version | grep -Po ${ver_regex})
		if [ "${link_ver}" != "${src_ver}" ]; then
			rm "${phpbin_link}" -f
			[ -f "${phpize_link}" ] && rm "${phpize_link}" -f
			[ -f "${phpfpm_link}" ] && rm "${phpfpm_link}" -f
			[ -f "${pecl_link}" ] && rm "${pecl_link}" -f
			[ -f "${pear_link}" ] && rm "${pear_link}" -f
		fi
	fi
	[ ! -f "${phpbin_link}" ] && ln -s ${phpbin_src} ${phpbin_link}
	[ ! -f "${phpize_link}" ] && ln -s ${phpize_src} ${phpize_link}
	[ ! -f "${phpfpm_link}" ] && ln -s ${phpfpm_src} ${phpfpm_link}
	[ ! -f "${pecl_link}" ] && ln -s ${pecl_src} ${pecl_link}
	[ ! -f "${pear_link}" ] && ln -s ${pear_src} ${pear_link}
}

php_fpm_conf() {
	if [ ! -d "${PHP_HOME}" ]; then
		echo "Can't find php install dir ${PHP_HOME}"
		return 1
	fi
	local tpl=${CUR_DIR}/php/php-fpm.conf.tpl
	IFS=""
	local data=$(read_file ${tpl})
	data=${data//\#PHP_FPM_PID_FILE\#/${PHP_FPM_PID_FILE}}
	data=${data//\#PHP_FPM_ERR_FILE\#/${PHP_FPM_ERR_FILE}}
	data=${data//\#PHP_FPM_LOG_LEVEL\#/${PHP_FPM_LOG_LEVEL}}
	data=${data//\#PHP_FPM_PROCESS_TIMEOUT\#/${PHP_FPM_PROCESS_TIMEOUT}}
	data=${data//\#PHP_FPM_PROCESS_MAX\#/${PHP_FPM_PROCESS_MAX}}
	data=${data//\#PHP_FPM_RLIMIT\#/${PHP_FPM_RLIMIT}}
	data=${data//\#WWW_USER\#/${WWW_USER}}
	data=${data//\#WWW_GROUP\#/${WWW_GROUP}}
	data=${data//\#PHP_FPM_LISTEN\#/${PHP_FPM_LISTEN}}
	data=${data//\#PHP_FPM_LISTEN_MODE\#/${PHP_FPM_LISTEN_MODE}}
	data=${data//\#PHP_FPM_PM_MODE\#/${PHP_FPM_PM_MODE}}
	data=${data//\#PHP_FPM_PM_START\#/${PHP_FPM_PM_START}}
	data=${data//\#PHP_FPM_PM_MAX_CHILDREN\#/${PHP_FPM_PM_MAX_CHILDREN}}
	data=${data//\#PHP_FPM_PM_MAX_REQUESTS\#/${PHP_FPM_PM_MAX_REQUESTS}}
	data=${data//\#TENGINE_WWW_HOME\#/${TENGINE_WWW_HOME}}

	echo ${data}
}

php_mk_fpm_conf() {
	php_fpm_conf > "${PHP_HOME}/etc/php-fpm.conf"
}

php_mk_sh() {
	if [ ! -d "${PHP_HOME}" ]; then
		echo "Can't find php install dir ${PHP_HOME}"
		return 1
	fi

	if [ ! -d "${PHP_FPM_LOG_DIR}" ]; then
		mkdir "${PHP_FPM_LOG_DIR}" -p
	fi

	local savefile=/etc/init.d/${PHP_BIN_PREFIX}-fpm
	local tpl=${CUR_DIR}/php/php-fpm.sh.tpl
	IFS=""
	local data=$(read_file ${tpl})
	data=${data//\#PHP_FPM_PID_FILE\#/${PHP_FPM_PID_FILE}}
	data=${data//\#PHP_BIN_PREFIX\#/${PHP_BIN_PREFIX}}
	data=${data//\#PHP_PKG_NAME\#/${PHP_PKG_NAME}}
	data=${data//\#PHP_FPM_CONF_FILE\#/"${PHP_HOME}/etc/php-fpm.conf"}

	echo ${data} > ${savefile}

	if [ -f "${savefile}" ]; then
		chmod +x ${savefile}
	fi
}